<?php
class Controllerstockfactory extends Controller {

	private $error = array();

	public function export(){
		$vendor_bill_id = I('get.vendor_bill_id');
		if(!$vendor_bill_id){
		  $vendor_bill_id = 0;
		}
		$this->load->model('stock/factory');
		$vendor_bill = $this->model_stock_factory->getVendorBill($vendor_bill_id);
		$data['vendor_bill'] = $vendor_bill;
		if(!$vendor_bill){
		  $this->load->language('error/not_found');

		  $this->document->setTitle($this->language->get('heading_title'));

		  $data['heading_title'] = $this->language->get('heading_title');

		  $data['text_not_found'] = $this->language->get('text_not_found');

		  $data['breadcrumbs'] = array();

		  $data['breadcrumbs'][] = array(
		    'text' => $this->language->get('heading_title'),
		    'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
		  );


		  $data['footer'] = $this->load->controller('common/footer');

		  $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
		}
		$vendor_bill_po = $this->model_stock_factory->getVendorBillPo($vendor_bill_id);
		//$po_num = $this->model_stock_factory->getVendorBillPoCount($vendor_bill_id);
		//$po_num = count($po_num);
		$vendor_info = $this->model_stock_factory->getVendorByVendorBillId($vendor_bill_id);

		//$po_total = $vendor_bill_po[0]['total'];
		$this->load->library('PHPExcel/PHPExcel');
		$objReader = PHPExcel_IOFactory::createReader('Excel5');
		$objPHPExcel = $objReader->load(DIR_SYSTEM . "template/vendor_bill_new_tpl.xls"); 
		// var_dump(DIR_SYSTEM . "template/vendor_bill_tpl.xls");die();
		$objPHPExcel->getProperties()->setCreator("Think-tec")
		           ->setLastModifiedBy("Think-tec")
		           ->setTitle("BHZ品牌厂商对账单")
		           ->setSubject("BHZ品牌厂商对账单")
		           ->setDescription("BHZ品牌厂商对账单")
		           ->setKeywords("BHZ, Think-tec")
		           ->setCategory("Think-tec");
		// $objPHPExcel->setActiveSheetIndex(0);
		$objActSheet = $objPHPExcel->getActiveSheet();
		/*
		$objActSheet->setCellValue('B2', $vendor_bill_po[0]['date_added']);
		$objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objActSheet->setCellValue('F2', $vendor_info['vendor_id']);
		$objActSheet->setCellValue('B3', $vendor_bill_po[0]['vendor_bill_id']);

		$objActSheet->setCellValue('F3', $vendor_info['vendor_name']);
		$objActSheet->setCellValue('F4', $vendor_info['firstname']);
		$objActSheet->setCellValue('F5', $vendor_info['telephone']);

		$objActSheet->setCellValue('D7', $po_num);
		$objActSheet->setCellValue('F7', '￥'.$po_total);

		$row_num = 8;
		$styleBorderOutline = array(
		  'borders' => array(
		    'outline' => array(
		      'style' => PHPExcel_Style_Border::BORDER_THIN,
		    ),
		  ),
		);
		$objPHPExcel->getActiveSheet()->insertNewRowBefore(9, count($vendor_bill_po));
		$count = 0;
		foreach ($vendor_bill_po as $key => $po_pd_info) {
		  $row_num++;
		  $objActSheet->setCellValue('A'.$row_num, $row_num-8);
		  $objActSheet->setCellValue('B'.$row_num, $po_pd_info['name'] . ' - ' . $po_pd_info['option_name']);
		  $objActSheet->setCellValue('C'.$row_num, '');
		  $objActSheet->setCellValue('D'.$row_num, $po_pd_info['qty']);
		  $objActSheet->setCellValue('E'.$row_num, $po_pd_info['unit_price']);
		  $objActSheet->setCellValue('F'.$row_num, $po_pd_info['price']);
		}
		*/
		// var_dump($vendor_bill_po);die();
		$objActSheet->setCellValue('B2', $vendor_bill['date_added']);//对账单创建时间
		$objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objActSheet->setCellValue('F2', $vendor_bill['vendor_bill_id']);//对账单编号
		$objActSheet->setCellValue('B3', $vendor_info['vendor_name']);//厂商名称
		$objActSheet->setCellValue('F3', $vendor_info['vendor_id']);//厂商编号
		$objActSheet->setCellValue('B4', $vendor_info['firstname']);//厂商联系人
		$objActSheet->setCellValue('F4', $vendor_info['telephone']);//厂商联系电话
		$objPHPExcel->getActiveSheet()->insertNewRowBefore(6, count($vendor_bill_po));
		$count = 6;
		foreach ($vendor_bill_po as $key => $info) {
		  $objActSheet->setCellValue('A'.$count, $info['refer_id']);
		  $objActSheet->setCellValue('B'.$count, $info['in_id']);
		  $objActSheet->setCellValue('C'.$count, $info['in_date']);
		  $objActSheet->setCellValue('D'.$count, $info['name'].'---'.$info['option_name']."\r\n".$info['sku']);
		  $objActSheet->setCellValue('E'.$count, $info['product_price']);
		  $objActSheet->setCellValue('F'.$count, $info['product_quantity']);
		  $objActSheet->setCellValue('G'.$count, round($info['product_price']*$info['product_quantity'], 2));
		  $count++;
		}
		// $objPHPExcel->getActiveSheet()->getStyle('A5'.':'.'O'.$row_num)->applyFromArray($styleBorderOutline);

		$objActSheet->setTitle('品牌厂商对账单');

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		ob_end_clean();
		// Redirect output to a client’s web browser (Excel2007)
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="VD_BILL_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');
		// If you're serving to IE over SSL, then the following may be needed
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0
		$objWriter->save('php://output'); 
		exit;
	}


	public function view(){

	$this->document->setTitle('查看品牌厂商对账单');

	$this->document->addScript('view/javascript/angular.js');
	$this->document->addScript('view/javascript/bhz_ctl.js');

	$this->load->model('stock/factory');
	$data['breadcrumbs'] = array();

	$data['breadcrumbs'][] = array(
	  'text' => $this->language->get('text_home'),
	  'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
	);

	$data['breadcrumbs'][] = array(
	  'text' => '品牌厂商对账单',
	  'href' => $this->url->link('stock/factory', 'token=' . $this->session->data['token'] , 'SSL')
	);

	$data['token'] = $this->session->data['token'];

	$id = I('get.vendor_bill_id');
	if(!$id){
	  $id=0;
	}


	if (isset($this->session->data['error'])) {
	  $data['error_warning'] = $this->session->data['error'];

	  unset($this->session->data['error']);
	} elseif (isset($this->error['warning'])) {
	  $data['error_warning'] = $this->error['warning'];
	} else {
	  $data['error_warning'] = '';
	}

	if (isset($this->session->data['success'])) {
	  $data['success'] = $this->session->data['success'];

	  unset($this->session->data['success']);
	} else {
	  $data['success'] = '';
	}

	$vendor_bill = $this->model_stock_factory->getVendorBill($id);
	$data['vendor_bill'] = $vendor_bill;
	$vendor_bill_po = $this->model_stock_factory->getVendorBillPo($id);
	// var_dump($vendor_bill_po);die();
	$data['vendor_bill_po'] = $vendor_bill_po;
	$vendor_bill_histories = $this->model_stock_factory->getVendorBillHistories($id);
	$data['vendor_bill_histories'] = $vendor_bill_histories;

	switch ($vendor_bill['status']) {
	  case '0':
	    $data['change_status_text'] = '平台确认对账单';
	    break;
	  // case '1':
	  //   $data['change_status_text'] = '品牌厂商确认对账单';
	  //   break;
	  case '2':
	    $data['change_status_text'] = '已打款';
	    break;
	  case '4':
	    $data['change_status_text'] = '已完成';
	    break;
	  default:
	    $data['change_status_text'] = '';
	    break;
	}

	$data['header'] = $this->load->controller('common/header');
	$data['column_left'] = $this->load->controller('common/column_left');
	$data['footer'] = $this->load->controller('common/footer');

	//保存对账单信息一下面remit方法需要使用
	$this->session->data['vendor_bill_id'] = I('get.vendor_bill_id');
	$this->session->data['vendor_id'] = $data['vendor_bill']['vendor_id'];

	$this->response->setOutput($this->load->view('stock/factory_view.tpl', $data));
	}

	public function save(){
	if ($this->request->server['REQUEST_METHOD'] == 'POST') {
	  $this->load->model('stock/factory');
	  $data = json_decode(file_get_contents('php://input'), true);
	  $filter = C('DEFAULT_FILTER');
	  $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
	  if(!$data['deliver_time'] || !$data['products']||!$data['vendor']){
	    $this->response->setOutput(json_encode(array('success'=>false, 'info'=>'数据不完整')));
	  }
	  else{
	    $po_id = $this->model_stock_factory->addPo($data, $this->user->getId());
	  }
	  $this->response->setOutput(json_encode(array('success'=>true, 'info'=>$po_id)));
	  return;
	}
	}

	public function delete() {
	$json = array();

	$this->load->model('stock/factory');

	$id = I('get.vendor_bill_id');
	if(!$id){
	  $id=0;
	}

	$vendor_bill = $this->model_stock_factory->getVendorBill($id);
	if(!$vendor_bill||$vendor_bill['status']!=0) {
	  $json['error'] = '非新增状态品牌厂商对账单不能删除';
	}
	else {
	  $this->model_stock_factory->deleteBill($id);
	  $json['success'] = '删除成功';
	}

	if (isset($this->request->server['HTTP_ORIGIN'])) {
	  $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
	  $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
	  $this->response->addHeader('Access-Control-Max-Age: 1000');
	  $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
	}

	$this->response->addHeader('Content-Type: application/json');
	$this->response->setOutput(json_encode($json));
	}



	protected function form(){
	$data['breadcrumbs'] = array();

	$data['breadcrumbs'][] = array(
	  'text' => $this->language->get('text_home'),
	  'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
	);

	$data['breadcrumbs'][] = array(
	  'text' => '品牌厂商对账单',
	  'href' => $this->url->link('stock/factory', 'token=' . $this->session->data['token'] , 'SSL')
	);

	$data['token'] = $this->session->data['token'];

	$id = I('get.po_id');
	if(!$id){
	  $id=0;
	}


	if (isset($this->session->data['error'])) {
	  $data['error_warning'] = $this->session->data['error'];

	  unset($this->session->data['error']);
	} elseif (isset($this->error['warning'])) {
	  $data['error_warning'] = $this->error['warning'];
	} else {
	  $data['error_warning'] = '';
	}

	if (isset($this->session->data['success'])) {
	  $data['success'] = $this->session->data['success'];

	  unset($this->session->data['success']);
	} else {
	  $data['success'] = '';
	}

	$po = $this->model_stock_factory->getPo($id);
	$data['po'] = $po;
	$po_products = $this->model_stock_factory->getPoProducts($id);
	$data['po_products'] = $po_products;

	$data['header'] = $this->load->controller('common/header');
	$data['column_left'] = $this->load->controller('common/column_left');
	$data['footer'] = $this->load->controller('common/footer');

	$this->response->setOutput($this->load->view('stock/factory.tpl', $data));
	}


	public function index() {

		$this->document->setTitle('品牌厂商对账单');

		$this->load->model('stock/factory');

		$this->getList();
	}

	protected function getList() {
	$page = I('get.page');
	if(!$page){
	  $page = 1;
	}
	$filter_vendor_bill_id = I('get.filter_vendor_bill_id');
	$filter_vendor_name = I('get.filter_vendor_name');
	$filter_year_month = I('get.filter_year_month');
	$filter_total = I('get.filter_total');
	$filter_date_added = I('get.filter_date_added');
	$filter_vendor_bill_status = I('get.filter_vendor_bill_status');

	if($filter_vendor_bill_id) {$filter['vendor_bill_id'] = $filter_vendor_bill_id;}
	if($filter_vendor_name) {$filter['vendor_name'] = array('like', '%'.$filter_vendor_name.'%');}
	if($filter_year_month) {$filter['DATE_FORMAT(vb.year_month, "%Y-%m")'] = $filter_year_month;}
	if($filter_total) {$filter['total'] = $filter_total;}
	if($filter_date_added) {$filter['date_added'] = $filter_date_added;}
	if($filter_vendor_bill_status || $filter_vendor_bill_status==0) {
	  $filter['vb.status'] = $filter_vendor_bill_status;
	}

	$data['filter_vendor_bill_id'] = $filter_vendor_bill_id;
	$data['filter_vendor_name'] = $filter_vendor_name;
	$data['filter_year_month'] = $filter_year_month;
	$data['filter_total'] = $filter_total;
	$data['filter_date_added'] = $filter_date_added;
	$data['filter_vendor_bill_status'] = $filter_vendor_bill_status;

	if($filter_vendor_bill_status=='') {
	  unset($data['filter_vendor_bill_status']);  
	  unset($filter['vb.status']);
	}

	$sort = I('get.sort');
	$order = I('get.order');
	if($order) {
	  $order = $order=='DESC'?'ASC':'DESC';
	}

	$sort_data = array(
	  'sort' => $sort?$sort:'vendor_bill_id',
	  'order' => $order?$order:'DESC',
	);

	$data['order'] = $sort_data['order'];
	$data['sort'] = $sort_data['sort'];

	$url .= '&order=' . $sort_data['order'];

	$data['sort_vendor_bill'] = $this->url->link('stock/factory', 'token=' . $this->session->data['token'] . '&sort=vb.vendor_bill_id' . $url, 'SSL');
	$data['sort_vendor_name'] = $this->url->link('stock/factory', 'token=' . $this->session->data['token'] . '&sort=vb.vendor_name' . $url, 'SSL');
	$data['sort_status'] = $this->url->link('stock/factory', 'token=' . $this->session->data['token'] . '&sort=vb.status' . $url, 'SSL');
	$data['sort_year_month'] = $this->url->link('stock/factory', 'token=' . $this->session->data['token'] . '&sort=vb.year_month' . $url, 'SSL');
	$data['sort_date_added'] = $this->url->link('stock/factory', 'token=' . $this->session->data['token'] . '&sort=vb.date_added' . $url, 'SSL');
	$data['sort_date_modified'] = $this->url->link('stock/factory', 'token=' . $this->session->data['token'] . '&sort=vb.date_modified' . $url, 'SSL');


	if($this->user->getLp()){
	  $filter['lg.user_id'] = $this->user->getId();
	}
	else if($this->user->getVp()){
	  $filter['lg.vendor_id'] = $this->user->getId();
	}
	else{
	  
	}

	$vendor_bill_list =  $this->model_stock_factory->getList($page, $filter, $sort_data);
	$bill_total = $this->model_stock_factory->getListCount($filter);
	foreach ($vendor_bill_list as $key => $value) {
	  $vendor_bill_list[$key]['status_name'] = getVendorBillStatus()[$value['status']];
	}

	$pagination = new Pagination();
	$pagination->total = $bill_total;
	$pagination->page = $page;
	$pagination->limit = $this->config->get('config_limit_admin');
	$pagination->url = $this->url->link('stock/factory', 'token=' . $this->session->data['token'] . '&page={page}', 'SSL');

	$data['pagination'] = $pagination->render();

	$data['breadcrumbs'] = array();

	$data['breadcrumbs'][] = array(
	  'text' => $this->language->get('text_home'),
	  'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
	);

	$data['breadcrumbs'][] = array(
	  'text' => '品牌厂商对账单',
	  'href' => $this->url->link('stock/factory', 'token=' . $this->session->data['token'] , 'SSL')
	);

	if (isset($this->session->data['error'])) {
	  $data['error_warning'] = $this->session->data['error'];

	  unset($this->session->data['error']);
	} elseif (isset($this->error['warning'])) {
	  $data['error_warning'] = $this->error['warning'];
	} else {
	  $data['error_warning'] = '';
	}

	if (isset($this->session->data['success'])) {
	  $data['success'] = $this->session->data['success'];

	  unset($this->session->data['success']);
	} else {
	  $data['success'] = '';
	}

	$data['vendor_bill_statuses'] = getVendorBillStatus();

	$data['token'] = $this->session->data['token'];

	$data['vendor_bills'] = $vendor_bill_list;

	$data['header'] = $this->load->controller('common/header');
	$data['column_left'] = $this->load->controller('common/column_left');
	$data['footer'] = $this->load->controller('common/footer');

	$this->response->setOutput($this->load->view('stock/factory_list.tpl', $data));
	}

	public function setVendorBillDiff() {
	if ($this->request->server['REQUEST_METHOD'] == 'POST') {
	  $this->load->model('stock/factory');
	  $data = json_decode(file_get_contents('php://input'), true);
	  $filter = C('DEFAULT_FILTER');
	  $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
	  // $id = I('post.po_id');
	  $id = $data['vendor_bill_id'];
	  if(!$id){
	    $id=0;
	  }
	  $vendor_bill = $this->model_stock_factory->getVendorBill($id);
	  //判断vendor_bill状态，如果是物流中心确认之后的状态则不允许在添加差额
	  if($vendor_bill['status'] > 1) {
	    $this->response->setOutput(json_encode(array('error'=>'不能修改物流中心确认之后的差价')));
	    return;
	  }

	  $difference = $data['difference'];
	  if($difference) {
	    $difference = (float)$difference;
	    $this->model_stock_factory->changeDifference($id, $difference);
	    $this->response->setOutput(json_encode(array('success'=>'修改对账单差价状态成功')));

	    //添加生成品牌商对账单操作记录
	    $this->load->model('user/user');
	    $user_info = $this->model_user_user->getUser($this->user->getId());
	    $comment = '修改对账单差价为：'.$difference;
	    $this->model_stock_factory->addVendorBillHistory($id, $this->user->getId(), $user_info['fullname'], $comment);   

	  } else {
	    $this->response->setOutput(json_encode(array('error'=>'差价不能为空')));
	  }
	  return;

	  $this->response->setOutput(json_encode(array('success'=>'修改采购单状态成功')));
	  return;
	} 
	}

	public function changeVendorBillStatus() {
	if ($this->request->server['REQUEST_METHOD'] == 'POST') {
	  $this->load->model('stock/factory');
	  $data = json_decode(file_get_contents('php://input'), true);
	  $filter = C('DEFAULT_FILTER');
	  $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
	  // $id = I('post.po_id');
	  $id = $data['vendor_bill_id'];
	  if(!$id){
	    $id=0;
	  }
	  $vendor_bill = $this->model_stock_factory->getVendorBill($id);
	  // var_dump($vendor_bill);die();
	  switch ($vendor_bill['status']) {
	    case '0':
	      $target_status = 1;
	      break;
	    case '1':
	      $target_status = 2;
	      break;
	    case '2':
	      $target_status = 3;
	      break;
	    case '4':
	      $target_status = 5;
	      break;
	    default:
	      $target_status = -1;
	      break;
	  }
	  if($target_status == -1) {
	    $this->response->setOutput(json_encode(array('error'=>'修改对账单状态失败')));
	  } else {
	    $this->model_stock_factory->changeVendorBillStatus($id, $target_status);
	    $this->response->setOutput(json_encode(array('success'=>'修改对账单状态成功')));

	    //添加生成品牌商对账单操作记录
	    $this->load->model('user/user');
	    $user_info = $this->model_user_user->getUser($this->user->getId());
	    $comment = '修改对账单状态为：'.getVendorBillStatus()[$target_status];
	    $this->model_stock_factory->addVendorBillHistory($id, $this->user->getId(), $user_info['fullname'], $comment);      

	  }
	  return;
	} 
	}

	public function exportLists() {

	$filter_vendor_bill_id = I('get.filter_vendor_bill_id');
	$filter_vendor_name = I('get.filter_vendor_name');
	$filter_year_month = I('get.filter_year_month');
	$filter_total = I('get.filter_total');
	$filter_date_added = I('get.filter_date_added');
	$filter_vendor_bill_status = I('get.filter_vendor_bill_status');
	if($filter_vendor_bill_status || $filter_vendor_bill_status==0) {
	  $filter['vb.status'] = $filter_vendor_bill_status;
	}

	if($filter_vendor_bill_id) {$filter['vendor_bill_id'] = $filter_vendor_bill_id;}
	if($filter_vendor_name) {$filter['vendor_name'] = array('like', '%'.$filter_vendor_name.'%');}
	if($filter_year_month) {$filter['DATE_FORMAT(vb.year_month, "%Y-%m")'] = $filter_year_month;}
	if($filter_total) {$filter['total'] = $filter_total;}
	if($filter_date_added) {$filter['date_added'] = $filter_date_added;}

	$sort = I('get.sort');
	$order = I('get.order');
	if($order) {
	  $order = $order=='DESC'?'ASC':'DESC';
	}

	$sort_data = array(
	  'sort' => $sort?$sort:'vendor_bill_id',
	  'order' => $order?$order:'DESC',
	);
	$this->load->model('stock/factory');
	$vendor_bill_list =  $this->model_stock_factory->getAllList($filter, $sort_data);



	$status_array = getvendorBillStatus();

	foreach ($vendor_bill_list as $key => $value) {
	  $save_data[$key] = array(
	    "vendor_bill_id"     =>  $value['vendor_bill_id'],
	    "vendor_name"        =>  $value['vendor_name'],
	    "status"                =>  $status_array[$value['status']],
	    "difference"            =>  $value['difference'],
	    "total"                 =>  $value['total'],
	    "real_total"            =>  $value['total']+$value['difference'],
	    "year_month"                    =>  date('Y-m',strtotime($value['year_month'])),
	    "date_added"            =>  $value['date_added'],
	    );
	  $difference = floatval($save_data[$key]['difference']);
	  $total = floatval($save_data[$key]['total']);
	  $save_data[$key]['po_total'] = number_format($total + $difference, 3);
	  # code...
	}

	$this->load->library('PHPExcel/PHPExcel');
	$objPHPExcel = new PHPExcel();    
	$objProps = $objPHPExcel->getProperties();    
	$objProps->setCreator("Think-tec");
	$objProps->setLastModifiedBy("Think-tec");    
	$objProps->setTitle("Think-tec Contact");    
	$objProps->setSubject("Think-tec Contact Data");    
	$objProps->setDescription("Think-tec Contact Data");    
	$objProps->setKeywords("Think-tec Contact");    
	$objProps->setCategory("Think-tec");
	$objPHPExcel->setActiveSheetIndex(0);     
	$objActSheet = $objPHPExcel->getActiveSheet(); 
	   
	$objActSheet->setTitle('Sheet1');
	$col_idx = 'A';
	$headers = array( '对账单编号',        '品牌厂商名称',   '状态',  '实际收货金额', '差额',     '应付货款','年月份', '添加日期');
	$row_keys = array('vendor_bill_id', 'vendor_name', 'status','total','difference','po_total', 'year_month',     'date_added');
	foreach ($headers as $header) {
	  $objActSheet->setCellValue($col_idx++.'1', $header);  
	}
	//添加物流信息
	$i = 2;
	foreach ($save_data as $rlst) {
	  $col_idx = 'A';
	  foreach ($row_keys as $rk) {
	    // $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]); 
	    $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
	  }
	  $i++;
	} 

	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

	ob_end_clean();
	// Redirect output to a client’s web browser (Excel2007)
	header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	header('Content-Disposition: attachment;filename="vendor_bill_'.date('Y-m-d',time()).'.xlsx"');
	header('Cache-Control: max-age=0');
	// If you're serving to IE 9, then the following may be needed
	header('Cache-Control: max-age=1');

	// If you're serving to IE over SSL, then the following may be needed
	header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
	header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
	header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
	header ('Pragma: public'); // HTTP/1.0
	$objWriter->save('php://output'); 
	exit;
	}
/*
重写方法，保存完成对接日志
	public function remit(){
	    $this->load->helper('yijiSignHelper');
	    $this->load->helper('dto/qftBatchTransfer.class');
	    $this->load->helper('YijipayClient');

	    if(isset($this->session->data['vendor_id'])){
	      $vendor_id = $this->session->data['vendor_id'];
	    }else{
	      $vendor_id = 0;
	    }

	    if(isset($this->session->data['vendor_bill_id'])){
	      $vendor_bill_id = $this->session->data['vendor_bill_id'];
	    }else{
	      $vendor_bill_id = 0;
	    }
	    
	    $this->load->model('stock/factory');
	    $vendors = $this->model_stock_factory->getVendors($vendor_id);
	    $sums= json_decode(file_get_contents('php://input'),true);
	    $sum = $sums['sum'];

	    $config = $this->getConfig();

	          $bank = array(
	                "中国农业银行" =>  "ABC",
	                "中国银行" =>  "BOC",
	                "交通银行" =>  "COMM",
	                "中国建设银行" =>  "CCB",
	                "中国光大银行" =>  "CEB",
	                "兴业银行" =>  "CIB",
	                "招商银行" =>  "CMB",
	                "民生银行" =>  "CMBC",
	                "中信银行" =>  "CITIC",
	                "重庆农村商业银行" =>  "CQRCB",
	                "中国工商银行" =>  "ICBC",
	                "中国邮政储蓄银行" =>  "PSBC",
	                "浦发银行" =>  "SPDB",
	                "中国银联" =>  "UNION",
	                "重庆银行" =>  "CQCB",
	                "广东发展银行" =>  "CGB",
	                "深圳发展银行" =>  "SDB",
	                "华夏银行" =>  "HXB",
	                "重庆三峡银行" =>  "CQTGB",
	                "平安银行" =>  "PINGANBK",
	                "上海银行" =>  "BKSH"
	          );

	          if(array_key_exists($vendors['bank_id'],$bank)){
	            $vendors['bank_id'] = $bank[$vendors['bank_id']];
	          }

	      $objReq = new qftBatchTransfer();
	      $objReq->setPartnerId($config['partnerId']);
	      $objReq->setReturnUrl('http://m.bhz360.com/system/weixin/success.html');
	      $objReq->setNotifyUrl('http://m.bhz360.com/system/weixin/success.html');
	      $objReq->setOrderNo($this->getBefstr().$vendor_bill_id);
	      $objReq->setMerchOrderNo($this->getBefstr().$vendor_bill_id);
	            $arr = array(
	                'itemMerchOrderNo' => $this->getBefstr().$vendor_bill_id,
	                'money'=>$sum,
	                'bankCode'=>$vendors['bank_id'],
	                'bankAccountNo'=>preg_replace('/ /', '', $vendors['card_id']),
	                'bankAccount'=>$vendors['card_name'],
	                'memo'=>'转账金额'.$sum
	              );
	            // var_dump($arr);die();
	      $objReq->settoPersonCardList([$arr]);
	      $objReq->setSignType("MD5");

	      $objReq->setpayerUserId($config['partnerId']);


	    //构建请求
	    $client = new YijiPayClient($config);
	    // var_dump($config);
	    // var_dump($objReq);
	    // die();
	    $response = $client->execute($objReq);
	    $this->response->setOutput(($response));
	}

    public function getBefstr(){
        return $order_befstr='BHZ2017VENDOR57'.substr(time(),'-5');
    }
*/
    public function remit() {
        $inputData = json_decode(file_get_contents('php://input'), true);
        if ($inputData['vbId'] && $inputData['sum']) {
            $this->load->model('stock/factory');
            $vbInfo = $this->model_stock_factory->getVendorBill($inputData['vbId']);
            $vbnpData = array(
                'vendor_bill_new_id' => $inputData['vbId'],
                'user_id' => $this->user->getId(),
                'user_name' => $this->user->getUserName(),
                'status' => 1,
            );
            $VBNPID = $this->model_stock_factory->addVBNP($vbnpData);
            $this->load->helper('yijiSignHelper');
            $this->load->helper('dto/qftBatchTransfer.class');
            $this->load->helper('YijipayClient');

            $config = $this->getConfig();
            $objReq = new qftBatchTransfer();
            $objReq->setPartnerId($config['partnerId']);
            $objReq->setpayerUserId($config['partnerId']);
            $objReq->setSignType("MD5");
            $YJFPK = 'BHZ2017VBP'.substr(time(), -10).$VBNPID;
            $objReq->setOrderNo($YJFPK);
            $objReq->setMerchOrderNo($YJFPK);
            $objReq->setReturnUrl('http://m.bhz360.com/index.php?route=payment/yiji_vbp/ret');//同步返回
            $objReq->setNotifyUrl('http://m.bhz360.com/index.php?route=payment/yiji_vbp/not');//异步返回
            $paymentInfo = $this->model_stock_factory->getPaymentInfoByVBID($inputData['vbId']);//根据对账单pk，获取收款方信息
            $bankCode = $this->_getBankCode($paymentInfo['bank_id']);
            if (false === $bankCode) {
                $returnInJson = array(
                    'status' => false,
                    'message' => '不支持的银行！'.$paymentInfo['bank_id'],
                );
            }else{
                $cardId = preg_replace('/[^0-9]/', '', $paymentInfo['card_id']);//过滤卡号列上的非数字
                $cardName = trim($paymentInfo['card_name']);
                $payParams = array(
                    'itemMerchOrderNo' => $YJFPK,
                    'money' => $inputData['sum'],
                    'bankCode' => $bankCode,
                    'bankAccountNo' => $cardId,
                    'bankAccount' => $cardName,
                    'memo' => $paymentInfo['vendor_name'].'，'.substr($vbInfo['year_month'], 0, 4).'年'.substr($vbInfo['year_month'], 5, 2).'月对账单（'.$inputData['vbId'].'）付款',
                );
                if (2 == $paymentInfo['iban_type']) {
                    $objReq->settoBusinessCardList(json_encode(array($payParams)));
                }else{
                    $objReq->settoPersonCardList(json_encode(array($payParams)));
                }
                $client = new YijiPayClient($config);
                $payUrl = $client->execute($objReq);
                $vbnpData = array(
                    'pay_params' => $payParams,
                    'pay_url' => $payUrl,
                );
                $this->model_stock_factory->updateVBNP($VBNPID, $vbnpData);
                $returnInJson = array(
                    'status' => true,
                    'message' => $payUrl,
                );
            }
        }else{
            $returnInJson = array(
                'status' => false,
                'message' => '对账单号、金额为空，打款失败！',
            );
        }
        $this->response->setOutput(json_encode($returnInJson));
    }

    //支付接口配置
    protected function getConfig(){
        return array(
            'partnerId' => '20161201020011981315', //商户ID
            'md5Key' => 'db3d0a81a79b6832c439bbf5ec92b77c', //商户Key
            
            'gatewayUrl' => "https://api.yiji.com/gateway.html", //生产环境
            // 'gatewayUrl' => "https://openapi.yijifu.net/gateway.html"    //测试环境
        );
    }

    //支付接口支持的银行列表
    protected function _getBankCode($bankName){
        $bankList = array(
            '中国农业银行'       => 'ABC',
            '中国银行'           => 'BOC',
            '交通银行'           => 'COMM',
            '中国建设银行'       => 'CCB',
            '中国光大银行'       => 'CEB',
            '兴业银行'           => 'CIB',
            '招商银行'           => 'CMB',
            '民生银行'           => 'CMBC',
            '中信银行'           => 'CITIC',
            '重庆农村商业银行'   => 'CQRCB',
            '中国工商银行'       => 'ICBC',
            '中国邮政储蓄银行'   => 'PSBC',
            '浦发银行'           => 'SPDB',
            '中国银联'           => 'UNION',
            '重庆银行'           => 'CQCB',
            '广东发展银行'       => 'CGB',
            '深圳发展银行'       => 'SDB',
            '华夏银行'           => 'HXB',
            '重庆三峡银行'       => 'CQTGB',
            '平安银行'           => 'PINGANBK',
            '上海银行'           => 'BKSH',
        );
        if (array_key_exists($bankName, $bankList)) {
            return $bankList[$bankName];
        }
        return false;
    }
}
